package com.fruit.controller;

import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * @Description: 服务容错性  断路器
 * @Author: LJ
 * @Date: 2018/11/1 16:43
 * @version:
 */
@RestController
//默认提示(当服务故障时返回)
@DefaultProperties(defaultFallback = "defaultFallback")
public class HystrixController {
	@Autowired
	private RestTemplate restTemplate;
	//超时配置(3秒) 默认1秒
//	@HystrixCommand(commandProperties = {
//			@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")
//	})

	@HystrixCommand(commandProperties = {
			@HystrixProperty(name = "circuitBreaker.enabled", value = "true"),  				//设置熔断
			@HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),	//请求数达到后才计算
			@HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"), //休眠时间窗10秒
			@HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60"),	//错误率百分60
	})
//	@HystrixCommand
	@GetMapping("/getProductInfoList")
	public String getProductInfoList(Integer number) {
		if (number % 2 == 0) {
			return "success";
		}
		return  restTemplate.getForObject("http://PRODUCT/product/list", String.class);

//		throw new RuntimeException("发送异常了");
	}

	private String fallback() {
		return "太拥挤了, 请稍后再试~~";
	}

	private String defaultFallback() {
		return "默认提示：太拥挤了, 请稍后再试~~";
	}
}
